<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Title</title>
  <style>
    #div1 {
      width: 100px;
      height: 100px;
      background: red;
      position: absolute;
    }

    #div2 {
      width: 100px;
      height: 100px;
      background: yellow;
      position: absolute;
      left: 110px;
    }
  </style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script>
  window.onload = function () {
    let d1 = new Drag("div1");
    d1.init();
    let d2 = new ChildDrag("div2");
    d2.init();
  };

  function Drag(obj) {
    this.obj = document.getElementById(obj);
    this.disX = 0;
    this.disY = 0;
  }

  Drag.prototype.init = function () {
    let This = this;
    this.obj.onmousedown = function (e) {
      let ev = e || window.e;
      This.fnDown(ev);
      document.onmousemove = function (e) {
        let ev = e || window.e;
        This.fnMove(ev);
      };
      document.onmouseup = function () {
        This.fnUp()
      };
      return false;
    }
  };
  Drag.prototype.fnDown = function (ev) {
    this.disX = ev.clientX - this.obj.offsetLeft;
    this.disY = ev.clientY - this.obj.offsetTop;
  };
  Drag.prototype.fnMove = function (ev) {
    this.obj.style.left = ev.clientX - this.disX + "px";
    this.obj.style.top = ev.clientY - this.disY + "px";
  };
  Drag.prototype.fnUp = function () {
    document.onmousemove = null;
    document.onmouseup = null;
  };

  function ChildDrag(id) {
    Drag.call(this, id);
  }

  extend(ChildDrag.prototype, Drag.prototype);

  ChildDrag.prototype.fnMove = function (ev) {
    let L = ev.clientX - this.disX;
    let T = ev.clientY - this.disY;
    if (L < 0) {
      L = 0;
    } else if (L > document.documentElement.clientWidth - this.obj.offsetWidth) {
      L = document.documentElement.clientWidth - this.obj.offsetWidth;
    }
    this.obj.style.left = L + "px";
    this.obj.style.top = T + "px";
  };


  function extend(obj1, obj2) {
    for (let attr in obj2) {
      obj1[attr] = obj2[attr];
    }
  }
</script>
</body>
</html>
